import constantRouterMap from '@/router/constantRoutes'
import asyncRouterMap from '@/router/asyncRoutes'

import authority from '@/utils/authority'

function getRouter() {
  const { menu = [], is_admin = false } = authority.get() || {}

  let addRouters = []

  // 过滤有权限的路由
  function permissionMenu(routerMap) {
    return routerMap.filter(item => {
      const hasPermission = menu.find(it => item.name === it)
      if (hasPermission && item.children && item.children.length) {
        item.children = permissionMenu(item.children)
      }
      return hasPermission
    })
  }

  // 获取当前角色所有权限的路由菜单
  const permissionRouter = () => {
    let routers = []
    if (is_admin) {
      addRouters = asyncRouterMap
      routers = [...constantRouterMap, ...asyncRouterMap]
    } else {
      addRouters = permissionMenu(asyncRouterMap)
      routers = [...constantRouterMap, ...addRouters]
    }
    return routers
  }

  const routers = permissionRouter()
  return {
    routers,
    addRouters
  }
}

const { routers, addRouters } = getRouter()

const permission = {
  state: {
    routers,
    addRouters
  },
  mutations: {
    SET_PERMISSION_ROUTER(state) {
      const { routers, addRouters } = getRouter()
      state.routers = routers
      state.addRouters = addRouters
    }
  },
  actions: {}
}

export default permission
